"use strict";

const crypto = require('crypto');
const Controller = require('../common/shop')

class UsersController extends Controller {

  //商铺入驻注册
  async register() {

    const {ctx, app} = this 
    const errors = ctx.validate({username: 'username', password: 'password'}, ctx.request.body)
    if (errors) return this.resData(4, '用户名或密码不合法', errors)
    let { username, password, captcha_code, captcha_key } = ctx.request.body
    let ur = await app.mysql.query('SELECT * FROM `user` WHERE `username`=?', [username])
    let cr = await app.mysql.query('SELECT * FROM `captcha` WHERE `code`=?', [captcha_code])

    if (!cr.length) {
      await app.mysql.query('UPDATE `captcha` SET `is_use`=? WHERE `key`=?', [1, captcha_key])
      return this.resData(1, '验证码错误', null)
    }

    if ((cr[0].expire < Date.now()) || cr[0].is_use) {
      return this.resData(2, '验证码已失效', null)
    }

    if (ur.length) {
      await app.mysql.query('UPDATE `captcha` SET `is_use`=? WHERE `code`=?', [1, captcha_code])
      return this.resData(3, '用户名已被占用', null)
    }

    await app.mysql.query('DELETE FROM `captcha` WHERE `key`=? OR `is_use`=? OR `expire`<?', [captcha_key, 1, Date.now()])

    this.tableName = 'shop'
    let shopResult = await this.add({shop_name: username})

    this.tableName = 'member_auth'
    await this.add({site_id: shopResult.insertId, member_username: username})

    await app.mysql.query('INSERT INTO  `user` (`site_id`, `username`, `password`, `create_time`, `update_time`) VALUES (?,?,?,?,?)', [shopResult.insertId, username, crypto.createHash('md5').update(password).digest('hex'), Date.now(), Date.now()])
    
    return this.resData(0, '注册成功', null)
  }

}

module.exports = UsersController